package com.linlin.song.bigwork.web.backend;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.linlin.song.bigwork.service.ProductPictureService;

/**
 * 处理图片上传和展示
 */
public class ProductPictureServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProductPictureService productPictureService  = new ProductPictureService();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    Long productId = Long.valueOf(request.getParameter("id"));
	    List<String> pictureNames;
        try {
            pictureNames = this.productPictureService.findByProductId(productId);
            request.setAttribute("pictureNames", pictureNames);
            request.getRequestDispatcher("/WEB-INF/view/backend/product_picture.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    //取得文件
	    Part filePart = request.getPart("image");
        String orgName = filePart.getSubmittedFileName();
        String suffix = orgName.substring(orgName.lastIndexOf("."));
        String name = UUID.randomUUID() + suffix;
        String picturePath = request.getServletContext().getRealPath("/resources/picture/product");
        File file = new File(picturePath, name);
        try(InputStream input = filePart.getInputStream();
            OutputStream output = new FileOutputStream(file);    
            ) {
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = input.read(buffer)) != -1){
                output.write(buffer, 0, len);
            }
        }
        //取得id
        Part idPart = request.getPart("id");
        try(InputStream input = idPart.getInputStream()){
            byte[] idBtye = new byte[(int)idPart.getSize()];
            input.read(idBtye);
            String idStr = new String(idBtye);
            Long productId = Long.valueOf(idStr);
            this.productPictureService.save(productId, name);
            response.getWriter().print("上传成功");
        } catch (SQLException e) {
            e.printStackTrace();
            file.delete();
            response.getWriter().print("上传失败");
        }
	}
}
